package com.yoshino.leetcode.interview150.dictTree;

class WordDictionary {
    private class Node {
        private boolean isEnd;
        private Node[] next;

        public Node() {
            isEnd = false;
            next = new Node[26];
        }
    }

    private Node root;
    public WordDictionary() {
        root = new Node();
    }
    
    public void addWord(String word) {
        Node cur = root;
        for (char c : word.toCharArray()) {
            if (cur.next[c - 'a'] == null) {
                cur.next[c - 'a'] = new Node();
            }
            cur = cur.next[c - 'a'];
        }
        cur.isEnd = true;
    }
    
    public boolean search(String word) {
        // 有特殊情况
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (c == '.') {
                for (int j = 0; j < 26; j++) {
                    if (cur.next[j] != null) {
                        boolean search = search(word, cur.next[j], i + 1);
                        if (search) {
                            return true;
                        }
                    }
                }
                return false;
            } else {
                if (cur.next[c - 'a'] == null) {
                    return false;
                }
                cur = cur.next[c - 'a'];
            }
        }
        return cur.isEnd;
    }
    public boolean search(String word, Node cur, int ind) {
        // 代表后续的字符串中有 。 出现，需额外判断返回值
        boolean isFlag = false;
        // 有特殊情况
        for (int i = ind; i < word.length(); i++) {
            char c = word.charAt(i);
            if (c == '.') {
                for (int j = 0; j < 26; j++) {
                    if (cur.next[j] != null) {
                        boolean search = search(word, cur.next[j], i + 1);
                        if (search) {
                            return true;
                        }
                    }
                }
                isFlag = true;
            } else {
                if (cur.next[c - 'a'] == null) {
                    return false;
                }
                cur = cur.next[c - 'a'];
            }
        }
        return !isFlag && cur.isEnd;
    }

}

/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary obj = new WordDictionary();
 * obj.addWord(word);
 * boolean param_2 = obj.search(word);
 */